import { useState, useEffect, useRef } from 'react'
import { Card, Input, Button, Table, Switch, message, Avatar, Tag, Drawer, Form, Select } from 'antd'
import type { GetProps } from 'antd'
import { UserOutlined, PlusCircleFilled, DeleteOutlined } from '@ant-design/icons'
import { getManagerList, changStatus, delManager, addManager, editManager } from '@/api/manager'
import ChooseImage from '@/components/ChooseImage'
import styles from './index.module.css'

type SearchProps = GetProps<typeof Input.Search>
const { Search } = Input

function Manager() {
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const limit = 10
  const [searchValue, setSearchValue] = useState('')
  const [managerList, setManagerList] = useState([])
  const [roles, setRoles] = useState([])

  useEffect(() => {
    getList()
  }, [page, limit, searchValue])
  const getList = () => {
    getManagerList(page, limit, searchValue).then(res => {
      console.log(res)
      if (res.status === 200) {
        setManagerList(res.data.list)
        setTotal(res.data.totalCount)
        setRoles(res.data.roles)
      }
    })
  }

  const onSearch: SearchProps['onSearch'] = (value, _e, info) => console.log(info?.source, value)
  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value)
  }
  // 点击分页
  const pageChange = (e: any) => {
    setPage(e.current)
  }
  // 修改状态
  const switchChange = (data: any) => {
    changStatus(data.id, { status: !data.status }).then(res => {
      if (res.status === 200) {
        message.success('修改成功')
        getList()
      }
    })
  }
  // 删除管理员
  const delManagerBtn = (data: any) => {
    delManager(data.id).then(res => {
      if (res.status === 200) {
        message.success('删除成功')
        getList()
      }
    })
  }
  // 添加/修改抽屉
  const [openDrawer, setOpenDrawer] = useState(false)
  const [editId, setEditId] = useState(0)
  const [form] = Form.useForm()
  const saveAddManagerBtn = () => {
    form.validateFields().then(values => {
      if (editId !== 0) {
        editManager(editId, { ...values, avatar: imgUrl }).then(res => {
          if (res.status === 200) {
            getList()
            message.success('修改成功')
            form.resetFields()
            setOpenDrawer(false)
          }
        })
        return
      }
      addManager({ ...values, avatar: imgUrl }).then(res => {
        if (res.status === 200) {
          getList()
          message.success('添加成功')
          form.resetFields()
          setOpenDrawer(false)
        }
      })
    })
  }
  const editManagerBtn = (data: any) => {
    setEditId(data.id)
    form.setFieldsValue({
      role_id: data.role_id,
      username: data.username,
      status: data.status
    })
    setImgUrl(data.avatar)
    setOpenDrawer(true)
  }
  const [imgUrl, setImgUrl] = useState('')
  const chooseImgRef = useRef<any>(null)
  const getImgUrl = (url: string) => {
    setImgUrl(url)
  }
  const openImgDrawer = () => {
    chooseImgRef.current.showModal()
  }
  const addManagerBtn = () => {
    setImgUrl('')
    setOpenDrawer(true)
  }
  const columns = [
    {
      title: '管理员',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Avatar size='large' src={data.avatar} icon={<UserOutlined />} />
          <div className='ml-10'>
            <p>{data.username}</p>
            <p>ID{data.id}</p>
          </div>
        </div>
      )
    },
    {
      title: '所属管理员',
      render: (data: any) => <p>{data.role.name}</p>
    },
    {
      title: '状态',
      render: (data: any) => (
        <Switch
          checked={data.status}
          onChange={() => {
            switchChange(data)
          }}
        ></Switch>
      )
    },
    {
      title: '操作',
      render: (data: any) => (
        <div>
          <Tag
            color='#108ee9'
            onClick={() => {
              editManagerBtn(data)
            }}
          >
            修改
          </Tag>
          <Tag
            color='#f50'
            onClick={() => {
              delManagerBtn(data)
            }}
          >
            删除
          </Tag>
        </div>
      )
    }
  ]

  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={saveAddManagerBtn}>
        提交
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setOpenDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  return (
    <>
      <Card>
        <div>
          <Search
            value={searchValue}
            placeholder='请输入管理员昵称'
            onSearch={onSearch}
            onChange={handleSearchChange}
            enterButton
            style={{ width: '20%', marginRight: '10px' }}
          />
          <Button
            type='primary'
            onClick={() => {
              setSearchValue('')
            }}
          >
            重置
          </Button>
        </div>
        <div className='mt-10'>
          <Button
            onClick={() => {
              addManagerBtn()
            }}
          >
            添加
          </Button>
        </div>
        <Table columns={columns} dataSource={managerList} rowKey='id' pagination={{ total }} onChange={pageChange} />
      </Card>
      <Drawer
        title={editId === 0 ? '添加管理员' : '修改管理员'}
        onClose={() => {
          setOpenDrawer(false)
        }}
        open={openDrawer}
        width='30%'
        footer={btn}
      >
        <Form form={form}>
          <Form.Item label='用户名' name='username' rules={[{ required: true, message: '请输入用户名!' }]}>
            <Input placeholder='请输入用户名' />
          </Form.Item>
          <Form.Item label='密码' name='password' rules={[{ required: editId === 0 ? true : false, message: '请输入密码!' }]}>
            <Input placeholder='请输入密码' />
          </Form.Item>
          <Form.Item label='头像' name='avatar'>
            {imgUrl && (
              <div style={{ position: 'relative' }}>
                <img src={imgUrl} className={styles.imgItem} alt='' style={{ width: 120, height: 120, objectFit: 'cover' }} />
                <div className={styles.delImage}>
                  <DeleteOutlined
                    style={{ color: '#fff', cursor: 'pointer', fontSize: '20px' }}
                    onClick={() => {
                      setImgUrl('')
                    }}
                  />
                </div>
              </div>
            )}
            <div className={styles.addPic} onClick={openImgDrawer}>
              <PlusCircleFilled />
            </div>
          </Form.Item>
          <Form.Item name='role_id' label='所属管理员' rules={[{ required: true, message: '请选择所属管理员!' }]}>
            <Select placeholder='请选择所属管理员' style={{ width: 180 }} options={roles} fieldNames={{ label: 'name', value: 'id' }} />
          </Form.Item>
          <Form.Item label='状态' name='status' initialValue={true}>
            <Switch defaultChecked></Switch>
          </Form.Item>
        </Form>
      </Drawer>
      <ChooseImage getImgUrl={getImgUrl} ref={chooseImgRef} />
    </>
  )
}

export default Manager
